package org.java.base.idea;

import java.lang.reflect.Field;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * 整理关于string StringBuilder StringBuffer
 *
 * @Author idea
 * @Date created in 6:51 下午 2020/5/1
 */
public class StringAndStringBuilderAndStringBuffer {


    private static void test() {
        String str2 = new String("hello");
        String str3 = str2.intern();
        String str1 = "hello";

        System.out.println(str1 == str3);
    }

    private static void test2(){
        String str1 = "test2";
        String str2 = "test"+"2";
        System.out.println(str1==str2);

        //往常量池里写数据
        String str3 = str2.intern();
        String str4 = "test2";
        System.out.println(str3==str4);
    }

    public static void test3() throws NoSuchFieldException, IllegalAccessException {
        String str = "test3";
        String str2 = "test3";
        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        char[] chars = (char[]) field.get(str);
        chars[1]='7';
        System.out.println(str+" "+str2);
    }


    public static void test4(){
        StringBuffer stb = new StringBuffer();
        //线程安全
        stb.append("a").append("bc").append("d");
        System.out.println(stb.toString());

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("k").append("j").append("p");
        System.out.println(stringBuilder);

        String str = "1"+"2"+"3"+"4";
        System.out.println(str);
    }


    public static void test5(){
        String s = new String("1");
        s.intern();
        String s2 = "1";
        System.out.println(s == s2);

        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
    }


    static final int MAX = 1000 * 10000;
    static final String[] arr = new String[MAX];

    public static void test6() throws Exception {
        Integer[] DB_DATA = new Integer[10];
        Random random = new Random(10 * 10000);
        for (int i = 0; i < DB_DATA.length; i++) {
            DB_DATA[i] = random.nextInt();
        }
        long t = System.currentTimeMillis();
        for (int i = 0; i < MAX; i++) {
            //这里面只会用到10个字符串
            //char 62232b
//            arr[i] =new String(String.valueOf(DB_DATA[i % DB_DATA.length]));
            //
            arr[i] = new String(String.valueOf(DB_DATA[i % DB_DATA.length])).intern();
        }

        System.out.println((System.currentTimeMillis() - t) + "ms");
        System.gc();
    }

    public static void main(String[] args) throws Exception {
        //perm 永久代
        //jdk8 metaspace 元空间
//        test3();
        test6();
        while(true){}
    }
}
